//
//  NewsWebViewController.m
//  suRead
//
//  Created by lidi on 15/11/8.
//  Copyright © 2015年 bao. All rights reserved.
//

#import "NewsWebViewController.h"
#import "Masonry.h"
#import "UIControl+Blocks.h"
#import "UIApplication+VisibleViewController.h"
#import "NewsBridge.h"
#import "NewsDetailViewController.h"
#import "ShareService.h"
#import "ServiceNews.h"
#import "AccountManager.h"
#import "LoginViewController.h"
#import "AppDelegate.h"

@interface NewsWebViewController ()<UIWebViewDelegate,LoginViewDelegate>
@property (nonatomic,strong) UIWebView *newsWebView;
@property (nonatomic,strong) NewsBridge *bridge;
@property (nonatomic,strong) NSString *refererString;
@property (nonatomic,strong) UIView *bottomBarView;
@property (nonatomic,strong) UIButton *buttonBack;
@end

@implementation NewsWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isBack = NO;

    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBarHidden = YES;
    [self setNeedsStatusBarAppearanceUpdate];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    __weak typeof(self) weak_self = self;
    
    self.bottomBarView = [UIView new];
    [self.view addSubview:self.bottomBarView];
    [self.bottomBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(weak_self.view);
        if (iPhoneX) {
            make.height.equalTo(@88.0f);
        } else {
            make.height.equalTo(@64.0f);
        }
    }];
    
    UIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonBack setImage:[UIImage imageNamed:@"button_backward"] forState:UIControlStateNormal];
    [self.bottomBarView addSubview:buttonBack];
    [buttonBack addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        //浏览器返回
        if (weak_self.newsWebView.canGoBack) {
            [weak_self.newsWebView goBack];
        } else {
            [weak_self.navigationController popViewControllerAnimated:YES];
            [weak_self dismissViewControllerAnimated:YES completion:^{
            }];
        }
    }];
    [buttonBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.bottomBarView).with.offset(8.0f);
        make.bottom.equalTo(self.bottomBarView);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@44.0f);
    }];
    
    UIButton *buttonWebViewBack= [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonWebViewBack setImage:[UIImage imageNamed:@"btn_refresh"] forState:UIControlStateNormal];
    [self.bottomBarView addSubview:buttonWebViewBack];
    [buttonWebViewBack addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        [weak_self.newsWebView reload];
    }];
    [buttonWebViewBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(buttonBack.mas_right).with.offset(8.0f);
        make.bottom.equalTo(self.bottomBarView);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@44.0f);
    }];
    
    if (self.hasShare) {
        UIButton *buttonShare= [UIButton buttonWithType:UIButtonTypeCustom];
        [buttonShare setImage:[UIImage imageNamed:@"icon_zb_share"] forState:UIControlStateNormal];
        [buttonShare addTarget:self action:@selector(shareButtonOnclick:) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomBarView addSubview:buttonShare];
        [buttonShare mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.bottomBarView.mas_right).with.offset(-8.0f);
            make.bottom.equalTo(self.bottomBarView);
            make.width.equalTo(@28.0f);
            make.height.equalTo(@44.0f);
        }];
    }
    
    if (self.hasClose) {
        UIButton *buttonClose = [UIButton buttonWithType:UIButtonTypeCustom];
        [buttonClose setImage:[UIImage imageNamed:@"read_close"] forState:UIControlStateNormal];
        [buttonClose addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
            [weak_self.navigationController popViewControllerAnimated:YES];
        }];
        [self.bottomBarView addSubview:buttonClose];
        [buttonClose mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.bottomBarView.mas_right).with.offset(0);
            make.bottom.equalTo(self.bottomBarView);
            make.width.equalTo(@44.0f);
            make.height.equalTo(@44.0f);
        }];
    }
    
    self.newsWebView = [UIWebView new];
    self.newsWebView.scalesPageToFit = YES;
    self.newsWebView.scrollView.bounces = NO;
    [self.newsWebView setAllowsInlineMediaPlayback:YES];
    [self.newsWebView setAllowsPictureInPictureMediaPlayback:YES];

    self.newsWebView.delegate=self;
    [self.view addSubview:self.newsWebView];
    [self.newsWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weak_self.view);
        make.top.mas_equalTo(self.bottomBarView.mas_bottom);
        if (iPhoneX) {
            make.bottom.equalTo(self.view).offset(-34.0f);
        } else {
            make.bottom.equalTo(self.view);
        }
    }];
    self.bridge = [NewsBridge bridgeForWebView:self.newsWebView webViewDelegate:self];
    [self.bridge setToNewsDetailCallBack:^(NSString *url) {
        NewsDetailViewController *controller = [NewsDetailViewController new];
        controller.urlString = url;
//        controller.f_thumbnail = weak_self.f_thumbnail;
        if ( [[[UIDevice currentDevice]systemVersion] floatValue] >= 8.0) {
            [weak_self showViewController:controller sender:weak_self];
        }else{
            [weak_self.navigationController pushViewController:controller animated:YES];
        }
    }];
    
    NSURL *url =[NSURL URLWithString:_urlString];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    //设置cookie
    [self setCookies];
    [self.newsWebView loadRequest:request];
    
    //添加消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appEnterForground:) name:kApplicationWillEnterForeground object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setCookies {
    if ([AccountManager sharedAccountManager].f_isLogined){
        // 定义 cookie 要设定的 host
        NSURL *cookieHost = [NSURL URLWithString:_urlString];
   
        // 设定 cookie
        NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:
                                [NSDictionary dictionaryWithObjectsAndKeys:
                                 [cookieHost host], NSHTTPCookieDomain,
                                 @"/", NSHTTPCookiePath,
                                 @"userid",  NSHTTPCookieName,
                                 [AccountManager sharedAccountManager].f_uid, NSHTTPCookieValue,
                                 nil]];
        
        // 设定 cookie 到 storage 中
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        // 设定 cookie
        NSHTTPCookie *cookie2 = [NSHTTPCookie cookieWithProperties:
                                 [NSDictionary dictionaryWithObjectsAndKeys:
                                  [cookieHost host], NSHTTPCookieDomain,
                                  @"/", NSHTTPCookiePath,
                                  @"mobile",  NSHTTPCookieName,
                                  [AccountManager sharedAccountManager].f_phone_num, NSHTTPCookieValue,
                                  nil]];
        
        // 设定 cookie 到 storage 中
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie2];
        // 设定 cookie
        NSHTTPCookie *cookie3 = [NSHTTPCookie cookieWithProperties:
                                 [NSDictionary dictionaryWithObjectsAndKeys:
                                  [cookieHost host], NSHTTPCookieDomain,
                                  @"/", NSHTTPCookiePath,
                                  @"encrypt",  NSHTTPCookieName,
                                  [AccountManager sharedAccountManager].f_encrypt, NSHTTPCookieValue,
                                  nil]];
        
        // 设定 cookie 到 storage 中
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie3];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    __weak typeof (self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //判断是否需要横屏
        if ([weakSelf.urlString rangeOfString:@"screen=w"].location != NSNotFound) {
            //强制横屏
            [weakSelf switchNewOrientation:UIInterfaceOrientationLandscapeRight];
        } else {
            [weakSelf switchNewOrientation:UIInterfaceOrientationPortrait];
        }
    });

}

- (void)viewWillDisappear:(BOOL)animated
{
    if (self.presentedViewController || self.isBack){
        [super viewWillDisappear:YES];
    }
    
    //改为竖屏
    [self switchNewOrientation:UIInterfaceOrientationPortrait];
}

//app进入前台
- (void)appEnterForground:(NSNotification *)notif {
    //判断是否需要横屏
    if ([self.urlString rangeOfString:@"screen=w"].location != NSNotFound) {
        //强制横屏
        [self switchNewOrientation:UIInterfaceOrientationLandscapeRight];
    } else {
        [self switchNewOrientation:UIInterfaceOrientationPortrait];
    }
}

//MARK: - 横竖屏
- (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation {
    
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (UIInterfaceOrientationIsPortrait(interfaceOrientation)) {
        appDelegate.allowRotation = NO; //关闭横屏仅允许竖屏
    } else {
        appDelegate.allowRotation = YES; //关闭横屏仅允许竖屏
    }
    
    NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
    [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
    NSNumber *orientationTarget = [NSNumber numberWithInt:interfaceOrientation];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    
    if (interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
        self.bottomBarView.hidden = YES;
        [self.bottomBarView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@0);
        }];
        
        if (!self.buttonBack) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
            [self.view addSubview:btn];
            __weak typeof(self) weakSelf = self;
            [btn addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
                //浏览器返回
                if (weakSelf.newsWebView.canGoBack) {
                    [weakSelf.newsWebView goBack];
                } else {
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                    [weakSelf dismissViewControllerAnimated:YES completion:^{
                    }];
                }
            }];
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(44.0f, 44.0f));
                if (@available(iOS 11.0, *)) {
                    make.top.equalTo(btn.superview.mas_safeAreaLayoutGuideTop);
                } else {
                    make.top.equalTo(btn.superview);
                }
                make.left.equalTo(btn.superview);
            }];
            self.buttonBack = btn;
        }
    } else {
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
    }
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

    NSLog(@"request.url.%@",request.URL);
    
    NSString *url = [request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //判断是否是登录
    if ([url rangeOfString:@"a=login"].location != NSNotFound) {
        //获取登录后跳转的url
        
        NSString *referer_url=[[url componentsSeparatedByString:@"referer="] lastObject];
        self.refererString = [self URLDecodedString:referer_url];
        
        //去登录
        UIStoryboard *personalCenterStoryBoard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
        LoginViewController *controller = [personalCenterStoryBoard instantiateViewControllerWithIdentifier:@"LoginViewController"];
        controller.delegate=self;
        controller.hidesBottomBarWhenPushed = YES;
        [self showViewController:controller sender:nil];
        
        return NO;
    }
    
    return YES;
}

- (void)refershUserInfo{
    //登录成功后跳转到referer url
    NSURL *url=[NSURL URLWithString:self.refererString];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    //设置cookie
    [self setCookies];
    [self.newsWebView loadRequest:request];
}

-(NSString *)URLDecodedString:(NSString *)str
{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}

- (void)shareButtonOnclick:(id)sender
{
    NSString *shareUrl_ = self.newsWebView.request.URL.absoluteString;
    if ([shareUrl_ rangeOfString:@"?"].location != NSNotFound)
    {
        shareUrl_ = [shareUrl_ stringByAppendingString:[NSString stringWithFormat:@"&uct=%@",[ServiceNews getAuthCode]]];
    }
    
    [ShareService share:self url:shareUrl_ title:self.titleString image:self.imgUrlString completion:nil];
}

-(void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion
{
    if (self.presentedViewController || self.isBack)
    {
        [super dismissViewControllerAnimated:flag completion:completion];
    }
}


@end
